// pages/reportForm/reportForm.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import * as echarts from '../../ec-canvas/echarts';
const util = require('../../utils/util');

//图表对象
let Chart1=null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图片前缀
    prefix:'http://bangnizu.oss-cn-hangzhou.aliyuncs.com/bangni/images/',    
    activeName: '',
    //图表
    ec1: {      
      lazyLoad: true 
    },
    //是否显示图表（避免遮挡）
    showChart1:true,   
    //部门名称
    departName:'暂无部门信息',

    //月份
    showMonth:false,
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    currentDateStr: util.timeFormatMonth(new Date()),
    //每月第一天
    beginDate:'',   
    //每月最后一天
    endDate: '',

    //类别数据    
    showType:false,
    noType:false,
    typeList:[],

    //图表数据
    showUse:false,
    noUse:false,
    useList:[],
    showUseChart:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    if(user){
      this.setData({
        departName: user.departObj[0].name,
      });
      
      //计算月份
      this.getMonthDay();        
    }else{
      wx.redirectTo({
        url: "/pages/login/login?reportForm="+'1'
      })
    }  
  },

  //计算月份
  getMonthDay(){
    let yy = new Date(new Date()).getFullYear();
    let mm = new Date(new Date()).getMonth();
    let beginDate = new Date(yy, mm, 1);
    let endDate = new Date(yy, mm+1, 0);

    this.setData({
      beginDate: util.timeFormatDay(beginDate),
      endDate: util.timeFormatDay(endDate)     
    })

    //获取类别数据
    this.getRunInformation();

    //获取图表数据
    //this.getChartData();
  },

  //获取类别数据
  getRunInformation(){
    let param={
      depart: app.globalData.userInfo.dataAuthorityOfUser.depart,
      beginDate:this.data.beginDate,
      endDate:this.data.endDate,
    }

    CommonService.runInformation(param).then(res=>{
      this.setData({
        showType:true        
      })

      console.log('类别统计');
      console.log(res);

      if(res.data.success && res.data.list.length){
        let result=res.data.list;
        result.forEach(item => {
          item.workHours=parseInt(item.workHours);
          item.work=parseInt(item.work);
        });

        this.setData({          
          typeList: result
        })
      }else{
        this.setData({         
          noType: true       
        })  
      }
    }).catch((error) => {                
    })  
  },

  onChange(event) {
    this.setData({
      activeName: event.detail,
    });
  },

  //获取图表数据
  getChartData(){
    let param={
      depart: app.globalData.userInfo.dataAuthorityOfUser.depart,
      beginDate:this.data.beginDate,
      endDate:this.data.endDate,
    }

    CommonService.usageInformation(param).then(res=>{
      this.setData({
        showUse:true               
      })
      console.log('图表数据');
      console.log(res);

      if(res.data.success && res.data.list.length){
        let result=res.data.list;
        let arr=[];
        result.forEach(item => {
          arr.push({
            value: item.xValue,
            name: item.xTitle
          })  
        });

        this.setData({ 
          showUseChart:true,
          useList: result        
        })

        //图表组件
        this.echartsComponnet1 = this.selectComponent('#mychart1');        

        //判断图表是否第一次绘制
        this.isHaveChart(Chart1, this.echartsComponnet1, arr);
      }else{
        this.setData({
          noUse: true       
        })
      }
    }).catch((error) => {                
    })    
  },

  //判断图表是否第一次绘制
  isHaveChart(chartObj,componnetObj,chartData){
    if (!chartObj){      
      //如果是第一次绘制，则初始化图表
      this.init_echarts(chartObj,componnetObj,chartData); 
    }else{
      //更新图表数据
      this.setOption(chartData);
    }    
  },

  //初始化图表
  init_echarts: function (chartObj,componnetObj,chartData) {      
    componnetObj.init((canvas, width, height) => {      
      chartObj = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      this.setOption(chartObj,chartData);
      
      return chartObj;       
    });
  },

  //更新图表数据
  setOption: function (chartObj,chartData) {    
    //清除
    chartObj.clear();
    //设置新数据
    chartObj.setOption(this.getOption(chartData));
  },

  //指定图表的配置项和数据
  getOption: function (data) {
    let option = {
      color:['#9E2024','#313539','#5C5E50','#19334C'],         
      grid: {
        left: '20%',
        right: '20%',
        top: '5%',
        bottom: '5%',
        containLabel: true,
      },     
      series: [
        {
            name: '访问来源',
            type: 'pie',
            radius: '50%',
            label:{
              normal:{
                fontSize : 12,                                                
                rich:{},
                formatter:'{b} {d}%'                  
              }
            },
            data: data,
            silent: true, 
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
      ]      
    }; 

    return option;
  },  

  //隐藏图表
  hideChart(){
    this.setData({       
      showChart1:false    
		})
  },

  //显示图表
  showChart(){
    this.setData({       
      showChart1:true     
		})
  },

  //显示月份
  onShowMonth(){
    this.setData({ 
			showMonth: true
    })
    //隐藏图表
    this.hideChart(); 
  },

  //隐藏月份
  onCloseMonth(){
    this.setData({
			showMonth: false
    })
    //显示图表
    this.showChart();
  },

  //确认月份
  onConfirmMonth(e){
    let yy = new Date(e.detail).getFullYear();
    let mm = new Date(e.detail).getMonth();
    let beginDate = new Date(yy, mm, 1);
    let endDate = new Date(yy, mm+1, 0);

    this.setData({
      currentDate: e.detail, 
      currentDateStr: util.timeFormatMonth(e.detail),
      beginDate: util.timeFormatDay(beginDate),
      endDate: util.timeFormatDay(endDate),
      showType:false,
      showUse:false,
      noType:false,
      noUse:false,
      showUseChart:false,
      typeList:[],
      useList:[],
    })    

    this.onCloseMonth();
    //获取类别数据
    this.getRunInformation();
    //获取图表数据
    this.getChartData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})